package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.mapper.TbCarouselChartMapper;
import com.zhentao.pojo.TbCarouselChart;
import com.zhentao.service.TbCarouselChartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@CrossOrigin
@RestController
@RequestMapping("lun")
public class LunController {
    @Autowired
    private TbCarouselChartService tbCarouselChartService;

    // 获取轮播图列表（分页）
    @GetMapping("/list")
    public Page<TbCarouselChart> list(@RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<TbCarouselChart> page = new Page<>(pageNum, pageSize);
        return tbCarouselChartService.page(page);
    }

    // 获取轮播图详情
    @GetMapping("/{id}")
    public TbCarouselChart getById(@PathVariable Integer id) {
        return tbCarouselChartService.getById(id);
    }

    // 上传路径：与配置文件 spring.resources.static-locations 保持一致（D:/img/image/）
    private static final String UPLOAD_PATH = "D:/img/image/";
    private static final String URL = "http://localhost:2000/";

    // 允许的图片类型
    private static final String[] ALLOWED_IMAGE_TYPES = {".jpg", ".jpeg", ".png", ".gif"};

    /**
     * 添加轮播图（适配本地存储 + 数据库记录）
     */
    @PostMapping("/add")
    public String add(
            @RequestParam("image") MultipartFile file,
            @RequestParam("topic") String topic,
            @RequestParam("title") String title) {

        // 1. 参数校验
        if (file.isEmpty()) {
            return "添加失败：请选择图片文件";
        }
        if (!StringUtils.hasText(topic)) {
            return "添加失败：主题不能为空";
        }
        if (!StringUtils.hasText(title)) {
            return "添加失败：备注不能为空";
        }

        // 2. 校验文件类型（通过文件名后缀）
        String originalFilename = file.getOriginalFilename();
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        boolean isAllowed = false;
        for (String type : ALLOWED_IMAGE_TYPES) {
            if (type.equals(fileSuffix)) {
                isAllowed = true;
                break;
            }
        }
        if (!isAllowed) {
            return "添加失败：仅支持 " + String.join(",", ALLOWED_IMAGE_TYPES) + " 格式";
        }

        // 3. 生成唯一文件名（避免重复覆盖）
        String fileName = UUID.randomUUID().toString() + fileSuffix;

        try {
            // 4. 确保上传目录存在（不存在则创建）
            File uploadDir = new File(UPLOAD_PATH);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs(); // 自动创建多级目录
            }

            // 5. 保存图片到本地目录（D:/img/image/xxx.jpg）
            File destFile = new File(UPLOAD_PATH + fileName);
            file.transferTo(destFile); // 写入文件

            // 6. 保存轮播图信息到数据库
            TbCarouselChart carousel = new TbCarouselChart();
            carousel.setTopic(topic);      // 主题
            carousel.setTitle(title);      // 备注
            carousel.setImage(URL+fileName);   // 存储唯一文件名（后续用于前端访问）
            // 若实体类有状态字段，可添加默认值：carousel.setStatus(1); // 1-启用，0-禁用
            boolean saveSuccess = tbCarouselChartService.save(carousel);
            if (saveSuccess) {
                // 成功：返回图片访问URL（前端可直接用）
                return "添加成功：图片URL=http://localhost:2000/" + fileName;
            } else {
                // 数据库保存失败，删除已上传的图片（避免垃圾文件）
                if (destFile.exists()) {
                    destFile.delete();
                }
                return "添加失败：数据库保存失败";
            }

        } catch (IOException e) {
            // 上传过程异常（如磁盘满、权限不足）
            e.printStackTrace();
            return "添加失败：图片上传异常，原因：" + e.getMessage();
        }
    }

    // 更新轮播图
    @PostMapping("/update")
    public boolean update(@RequestParam("id") Integer id,
                          @RequestParam(value = "image", required = false) MultipartFile file,
                          @RequestParam("topic") String topic,
                          @RequestParam("title") String title) throws IOException {
        TbCarouselChart carouselChart = tbCarouselChartService.getById(id);
        if (carouselChart == null) {
            return false;
        }

        // 如果上传了新图片，删除旧图片并上传新图片
        if (file != null && !file.isEmpty()) {
            String oldFileName = carouselChart.getImage();
            File oldFile = new File(UPLOAD_PATH + oldFileName);
            if (oldFile.exists()) {
                oldFile.delete();
            }

            String newFileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            file.transferTo(new File(UPLOAD_PATH + newFileName));
            carouselChart.setImage(URL+newFileName);
        }

        // 更新其他字段
        carouselChart.setTopic(topic);
        carouselChart.setTitle(title);

        return tbCarouselChartService.updateById(carouselChart);
    }

    // 删除轮播图
    @PostMapping("/delete/{id}")
    public boolean delete(@PathVariable Integer id) {
        TbCarouselChart carouselChart = tbCarouselChartService.getById(id);
        if (carouselChart == null) {
            return false;
        }
        // 删除图片文件
        String fileName = carouselChart.getImage();
        File file = new File(UPLOAD_PATH + fileName);
        if (file.exists()) {
            file.delete();
        }
        // 删除数据库记录
        return tbCarouselChartService.removeById(id);
    }
    //根据topic 和 title查询轮播图

    // 根据 topic 和 title 查询轮播图
    @GetMapping("/search")
    public  Page<TbCarouselChart> list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String topic,
            @RequestParam(required = false) String title) {
        Page<TbCarouselChart> page = new Page<>(pageNum, pageSize);
        QueryWrapper<TbCarouselChart> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(topic)) {
            queryWrapper.like("topic", topic);
        }
        if (StringUtils.hasText(title)) {
            queryWrapper.like("title", title);
        }
        return tbCarouselChartService.page(page, queryWrapper);
    }


}
